<template>
   <el-form
      ref="departForm"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="depart-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="部门等级" prop="grade">
        <el-select v-model="ruleForm.grade" placeholder="部门等级" @change="changeGrade()">
          <el-option label="1级部门" :value="1" />
          <el-option label="2级部门" :value="2" />
          <el-option label="3级部门" :value="3" />
          <el-option label="4级部门" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="父级节点" prop="pid">
        <el-select v-model="ruleForm.pid" placeholder="父级节点">
          <el-option v-for="item in state.parent_arr" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="ruleForm.remark"  />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(departForm)">
          保存
        </el-button>
        <el-button @click="clearForm(departForm)">清空</el-button>
      </el-form-item>
    </el-form>

    <div class="showDepartTree">
        <el-input class="treeFilter" v-model="keyword" placeholder="查询节点" :suffix-icon="Search" />
        <el-tree :data="state.treeData"  ref="treeRef" show-checkbox node-key="id" :props="defaultProps" :expand-on-click-node="false"   :default-expand-all="true" :filter-node-method="filterNode" >
          <template #default="{ node, data }">
          <span class="custom-tree-node">
        <span>{{ node.label }}</span>
        <span class="opt-icon">
          <!-- <el-button
            class="el-icon-plus"
            type="primary"
            @click="() => append(data)">
            <el-icon><Plus /></el-icon>
          </el-button> -->
            <el-icon  @click="() => remove(node, data)"><Delete /></el-icon>
        </span>
      </span>
      </template>
        </el-tree>
   
   
   </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules} from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {getAllList, getAllTreeData, getListByGrade, saveData,removeById } from '@/api/depart'
import { ElMessage, ElMessageBox } from 'element-plus'
const formSize = ref('default')
const departForm = ref<FormInstance>()

const keyword = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
watch(keyword, (val) => {
  treeRef.value!.filter(val)
})
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}
const defaultProps = {
  children: 'children',
  label: 'name',
}
const state=reactive({
  dialogShow:false,
  parent_arr:[],
  treeData:[
  {
    id: 1,
    label: '研究院',
    children: [
      {
        id: 2,
        label: '路由器团队-张博组',
        children: [
          {
            id: 9,
            label: '研发组',
            children: [
                {
                    id: 101,
                    label: '前端组',
                },
                {
                    id: 102,
                    label: '底层组',
                },
                {
                    id: 103,
                    label: '大数据组',
                },
             ],
          },
          {
            id: 10,
            label: '测试',
          },
        ],
      },
     
    ],
  },
]
})

const ruleForm = reactive({
    name: 'Hello',
    grade: 1,
    pid: 0,
    remark:''
  })
    
  const rules = reactive<FormRules<RuleForm>>({
    name: [
      { required: true, message: '请输入名称', trigger: ['blur','change'] },
      { min: 0, max: 30, message: '长度限制不超过30字符', trigger: ['blur','change'] },
    ],
    grade: [
      {
        required: true,
        message: '请选择级别',
        trigger: 'change',
      },
    ],
    pid: [
      {
        required: true,
        message: '请选择父级节点',
        trigger: 'change',
      },
    ],
  })
  const append=(data)=> {
        // const newChild = { id: id++, label: 'testtest', children: [] };
        // if (!data.children) {
        //   this.$set(data, 'children', []);
        // }
        // data.children.push(newChild);
      }
  const remove=(node, data) => {
    ElMessageBox.confirm('你确定要删除当前项吗',  '确认提示').then(async()=>{
            console.log("~~~~~~~~~~~~~~~~~~~~ininininin")
            removeById({id:data.id}).then(res=>{
            console.log(res)
            ElMessage.success(res.msg)
            getAllData()
          })
           
          })
  
      }
  //切换等级，查询对应的部门节点
const changeGrade=()=>{
  ruleForm.pid=null
  let curGrade=ruleForm.grade
  if(curGrade>0){
    getParantGrade(curGrade-1)
  }
}

const getParantGrade=async(p_grade)=>{
  getListByGrade({grade:p_grade}).then(res => {
    state.parent_arr=res.data||[]
    console.log(state.parent_arr,"~~getParantGrade~~~getParantGrade~~~")
   })
}
const getAllData=async()=>{
  getAllTreeData().then(res => {
    state.treeData=res.data||[]
    console.log(res,"~~getAllTreeData~~~rrrrrrr~~~")
   })
}
const clearForm =  () => {
    ruleForm['name']='' 
    ruleForm['grade']=null
    ruleForm['pid']=null
    ruleForm['remark']='' 
  
  }

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        saveData(ruleForm).then(res => {
            console.log(res,"~~~submitForm~~~~~")
            getAllData()
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
onMounted(()=>{
  getAllData()
})
</script>
<style lang="scss">
.el-input {
    width: 300px;
}
form.el-form.el-form--default.el-form--label-right.depart-ruleForm {
    width: 800px;
    margin: auto;
    padding: 60px;
    .el-input.el-input--default {
    width: 300px;
}
.el-textarea.el-input--default {
    width: 300px;
}
}

.el-tree {
    background: #a1d4f359;
    width: 80%;
    height: 800px;
    margin: auto;
    padding-top: 50px;
    padding-left: 25px;
}

.el-input {
    width: 300px;
}

.el-input.treeFilter {
    position: absolute;
    top: 10px;
    left: 12%;
    z-index: 1000;
}

.showDepartTree {position: relative;}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
    padding-right: 8px;

    span.opt-icon {
    color: #409eff;
    margin-left: 10px;
    vertical-align: middle;
    line-height: 12px;
}
  }
</style>